#include <iostream>
#include <ctime>
#include <cassert>
#include "Protocal.hpp"
#include "Socket.hpp"

void Usage(const std::string &proc)
{
    std::cout << "\nUsage: " << proc << " serverip serverport\n"
              << std::endl;
}

// ./ClienCal serverip serverport
int main(int argc, char *argv[])
{
    // 手册
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }

    std::string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);
    // 创建sockfd
    Sock sockfd;
    sockfd.Socket();
    // connect连接
    bool r = sockfd.Connect(serverip, serverport);
    if (!r)
        return 1;
    // 随机
    srand(time(nullptr) ^ getpid());

    // 进行cnt次测试
    int cnt = 1;
    const string oper = "+-*/%=#";
    std::string buffer_stream; // 这个是不是必须放在while循环外面？
    while (cnt <= 10)
    {
        std::cout << "============" << "第" << cnt++ << "次测试" << "================" << std::endl;
        // 创建x和y和op符号
        int x = rand() % 100 + 1;
        // cout<<"x"<<x<<endl;
        usleep(1234);
        int y = rand() % 10;
        // cout<<"y"<<y<<endl;

        usleep(5678);
        char op = oper[rand() % oper.size()];
        // cout<<"op"<<op<<endl;

        // 初始化req对象
        Request req(x, y, op);
        req.DebugPrint();

        std::string content;
        // 序列化
        r = req.Serialize(&content);

        // 添加报头
        content = Encode(content);
        // 发送信息

        //  std::cout << "content:" << content << "xxxxx" << std::endl;
        write(sockfd.Getsockfd(), content.c_str(), content.size());
        // write(sockfd.Getsockfd(), content.c_str(), content.size());
        // write(sockfd.Getsockfd(), content.c_str(), content.size());
        // write(sockfd.Getsockfd(), content.c_str(), content.size());
        // write(sockfd.Getsockfd(), content.c_str(), content.size());
        // std::cout << "=================================================" << std::endl;

        // 用buffer读取信息
        char buffer[128];
        ssize_t n = read(sockfd.Getsockfd(), buffer, sizeof(buffer)); // 在这里阻塞了

        if (n > 0)
        {
            buffer[n] = 0;
            buffer_stream += buffer;
            // 解析报头
            std::string content;
            // std::cout << "读到的响应" << buffer_stream << std::endl;
            //  将buffer_stream也就是收到的服务端发来的所有信息，提取报文，解析报头
            Decode(buffer_stream, &content);
            //  std::cout << "解码响应" << buffer_stream << std::endl;
            // 反序列化
            Response res;
            res.Deserialize(content);

            res.DebugPrint();
        }
        std::cout << "=================================================" << std::endl;
        sleep(1);
        // break;
    }

    // 关闭sockfd
    sockfd.Close();
    return 0;
}